<template>
  <div style="height: 100%">
    <a-spin :spinning="isTableLoading" wrapperClassName="spinning-container">
      <div class="header-container" ref="headerContainer">
        <page-header :title="l('LanguageTexts')"></page-header>
        <a-card :bordered="false">
          <a-button type="primary" @click="backLanguageList">
            <rollback-outlined />
            {{ l('BackLanguageList') }}
          </a-button>
          <a-button @click="refresh">
            <reload-outlined />
            {{ l('Refresh') }}
          </a-button>
          <p></p>
          <p></p>
          <a-form :model="form" :layout="'vertical'" @submit.prevent="getSearchData" ref="formRef">
            <a-row :gutter="8">
              <!-- 搜索 -->
              <a-col :sm="24">
                <a-form-item>
                  <a-input-search
                    name="filterText"
                    :placeholder="l('SearchWithThreeDot')"
                    @search="getSearchData"
                    enterButton
                    v-model:value="filterText"
                    v-model="filterText"
                  />
                </a-form-item>
              </a-col>
              <!-- 源语言 -->
              <a-col :sm="6">
                <a-form-item
                  :label="l('BaseLanguage')"
                  name="baseLanguageName"
                  :rules="[{ required: true, message: l('ThisFieldIsRequired') }]"
                >
                  <a-select
                    :placeholder="l('BaseLanguage')"
                    @change="getSearchData"
                    v-model:value="form.baseLanguageName"
                  >
                    <a-select-option
                      v-for="item in ILanguageInfo"
                      :key="item.name"
                      :value="item.name"
                    >
                      {{ item.displayName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!-- 目标语言 -->
              <a-col :sm="6">
                <a-form-item
                  :label="l('TargetLanguage')"
                  name="targetLanguageName"
                  :rules="[{ required: true, message: l('ThisFieldIsRequired') }]"
                >
                  <a-select
                    :placeholder="l('TargetLanguage')"
                    @change="getSearchData"
                    v-model:value="form.targetLanguageName"
                  >
                    <a-select-option
                      v-for="item in ILanguageInfo"
                      :key="item.name"
                      :value="item.name"
                    >
                      {{ item.displayName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!-- 源 -->
              <a-col :sm="6">
                <a-form-item
                  :label="l('Source')"
                  name="sourceName"
                  :rules="[{ required: true, message: l('ThisFieldIsRequired') }]"
                >
                  <a-select
                    :placeholder="l('Source')"
                    @change="changeSource"
                    v-model:value="form.sourceName"
                  >
                    <a-select-option v-for="item in sources" :key="item.name" :value="item.name">
                      {{ item.name }}
                      {{
                        item.name === appConsts.localization.defaultLocalizationSourceName
                          ? '（当前）'
                          : ''
                      }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <!-- 目标值 -->
              <a-col :sm="6">
                <a-form-item
                  :label="l('TargetValue')"
                  :rules="[{ required: true, message: l('ThisFieldIsRequired') }]"
                >
                  <a-select
                    :placeholder="l('TargetValue')"
                    @change="getSearchData"
                    v-model:value="form.targetValueFilter"
                  >
                    <a-select-option value="ALL">
                      {{ l('All') }}
                    </a-select-option>
                    <a-select-option value="EMPTY">
                      {{ l('EmptyOnes') }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
      </div>

      <!-- table -->
      <div class="table-container">
        <a-table
          size="middle"
          :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data-source="dataList"
          :pagination="{
            total: totalItems,
            current: pageNumber,
            pageSize: pageSize,
            showTotal: showTotalInfo,
            showQuickJumper: true,
            showSizeChanger: true,
            change: pageNumberChange,
            showSizeChange: pageNumberChange,
            pageSizeOptions: pageSizeOptions,
            size: 'middle',
          }"
          @change="tableChange"
        >
          <!-- tbody插槽 -->
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'creationTime'">
              {{ _moment(record.creationTime) }}
            </template>
            <template v-if="column.key === 'actions'">
              <a class="table-edit" @click="edit(record)"> <edit-outlined />{{ l('Edit') }} </a>
            </template>
          </template>
        </a-table>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { PagedListingComponentBase, IPagedRequestDto } from '/@/shared/component-base';
  import {
    LanguageServiceProxy,
    LanguageTextListDto,
    UpdateLanguageTextInput,
  } from '/@/shared/service-proxies';
  import { defineComponent } from 'vue';
  import { ReloadOutlined, RollbackOutlined, EditOutlined } from '@ant-design/icons-vue';
  import EditLanguageTexts from './edit-language-texts/edit-language-texts.vue';
  import { ColumnType } from 'ant-design-vue/lib/table';

  export default defineComponent({
    name: 'language-texts',
    mixins: [PagedListingComponentBase],
    components: {
      ReloadOutlined,
      RollbackOutlined,
      EditOutlined,
    },
    data() {
      return {
        form: {
          sourceName: '',
          baseLanguageName: '',
          targetLanguageName: '',
          targetValueFilter: '',
        },
        // 请求参数
        filterText: '',
        dataList: [] as LanguageTextListDto[],
        // 语言下拉
        ILanguageInfo: new Array<any>(),
        // 源
        sources: new Array<any>(),
        languageServiceProxy: new LanguageServiceProxy(),
        // 请求参数
      };
    },
    created() {
      this.ILanguageInfo = abp.localization.languages;
      this.sources = abp.localization.sources;

      this.fillServiceProxy();

      this.form.baseLanguageName =
        this.ILanguageInfo.find((item) => item.isDefault)?.name || 'zh-Hans';
      this.form.targetLanguageName =
        this.ILanguageInfo.find((item) => item.name === this.$route.query.lang)?.name || 'zh-Hans';
      this.form.sourceName =
        this.sources.find((source) => {
          return source.name === this.appConsts.localization.defaultLocalizationSourceName;
        }).name || this.sources[0]?.name;
      this.form.targetValueFilter = 'ALL';
    },
    methods: {
      /** 改变源 */
      changeSource(e): void {
        if (e === this.appConsts.localization.defaultLocalizationSourceName) {
          this.columns = this.getColumns();
        } else {
          this.columns = this.getColumns().filter((item) => item.key !== 'actions');
        }
      },
      /**
       * 获取数据
       */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        this.languageServiceProxy
          .getLanguageTexts(
            this.form.sourceName,
            this.form.baseLanguageName,
            this.form.targetLanguageName,
            this.form.targetValueFilter,
            this.filterText,
            request.sorting,
            request.maxResultCount,
            request.skipCount,
          )
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      /** 获取列 */
      getColumns(): ColumnType<LanguageTextListDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('Key'),
            dataIndex: 'key',
            ellipsis: true,
            key: 'key',
          },
          {
            title: this.l('BaseValue'),
            dataIndex: 'baseValue',
            ellipsis: true,
            key: 'baseValue',
          },
          {
            title: this.l('TargetValue'),
            dataIndex: 'targetValue',
            ellipsis: true,
            key: 'targetValue',
          },
          {
            title: this.l('Actions'),
            dataIndex: 'actions',
            ellipsis: true,
            key: 'actions',
            fixed: 'right',
            align: 'center',
            width: 250,
          },
        ];
      },
      /** 编辑语言 */
      edit(item: LanguageTextListDto): void {
        let senItem = Object.assign(item, {
          baseLanguageName: this.form.baseLanguageName,
          baseLanguageNameText: this.ILanguageInfo.find(
            (item) => item.name === this.form.baseLanguageName,
          ).displayName,
          targetLanguageNameText: this.ILanguageInfo.find(
            (item) => item.name === this.form.targetLanguageName,
          ).displayName,
          targetLanguageName: this.form.targetLanguageName,
          sourceName: this.form.sourceName,
          value: item.targetValue,
          key: item.key,
        });
        let updateLanguageinput: UpdateLanguageTextInput = new UpdateLanguageTextInput();
        updateLanguageinput.init(senItem);
        this.modalHelper
          .create(EditLanguageTexts, {
            editItem: senItem,
          })
          .subscribe((res) => {
            if (res) {
              this.refresh();
            }
          });
      },
      /**
       * 返回语言列表
       */
      backLanguageList(): void {
        this.$router.push({
          path: '/system/languages',
        });
      },
    },
  });
</script>

<style scoped lang="less">
  .subscriptionEndUtc {
    text-align: center;
  }

  // table
  .list-table {
    i {
      margin-right: 10px;
    }
  }

  .table-edit {
    .anticon {
      margin-right: 10px;
    }
  }

  .table-delete,
  .ant-dropdown-link {
    margin-left: 20px;
  }
</style>
